<template>
  <div class="product-container">
    <div class="table-container">
      <avue-crud
        ref="crudRef"
        :data="data"
        :option="option"
        :page="page"
        v-model:page="page"
        @size-change="sizeChange"
        @current-change="currentChange"
        @search-change="searchChange"
        @search-reset="searchReset"
        @on-load="onLoad"
        @row-save="onSubmit"
        @row-update="onUpdate"
        @row-del="onDelete"
        :loading="loading"
      >
      </avue-crud>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getFruitPage, addFruit, updateFruit, deleteFruit, uploadImage } from '@/api/product'
import { getCategoryPage } from '@/api/category'

// 表格配置
const option = reactive({
  align: 'center',
  menuAlign: 'center',
  searchMenuSpan: 6,
  border: true,
  index: true,
  viewBtn: true,
  editBtn: true,
  delBtn: true,
  page: true,
  pageSizes: [10, 20, 30, 50],
  paginationAlign: 'center',
  searchShowBtn: true,
  searchResetBtn: true,
  column: [
    {
      label: '商品名称',
      prop: 'name',
      search: true,
      span: 24,
      rules: [
        { required: true, message: '请输入商品名称', trigger: 'blur' }
      ]
    },
    {
      label: '商品主图',
      prop: 'imageUrl',
      type: 'upload',
      span: 24,
      listType: 'picture-card',
      limit: 10,
      action: 'http://localhost:8081/api/file/upload/image',
      propsHttp: {
        res: 'data',
        url: 'url',
        name: 'originalFilename'
      },
      rules: [
        { required: true, message: '请上传商品图片', trigger: 'change' }
      ]
    },
    {
      label: '原价',
      prop: 'price',
      type: 'number',
      precision: 2,
      rules: [
        { required: true, message: '请输入商品价格', trigger: 'blur' }
      ]
    },
    {
      label: '折扣价',
      prop: 'discountPrice',
      type: 'number',
      precision: 2
    },
    {
      label: '库存',
      prop: 'stock',
      type: 'number',
      rules: [
        { required: true, message: '请输入商品库存', trigger: 'blur' }
      ]
    },
    {
      label: '销量',
      prop: 'sales',
      type: 'number',
      addDisplay: false,
      editDisplay: false
    },
    {
      label: '商品分类',
      prop: 'categoryId',
      type: 'select',
      dicData: [],
      rules: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
      ]
    },
    {
      label: '产地',
      prop: 'origin',
      rules: [
        { required: true, message: '请输入产地', trigger: 'blur' }
      ]
    },
    {
      label: '规格',
      prop: 'specifications',
      rules: [
        { required: true, message: '请输入规格', trigger: 'blur' }
      ]
    },
    {
      label: '保质期',
      prop: 'shelfLife',
      rules: [
        { required: true, message: '请输入保质期', trigger: 'blur' }
      ]
    },
    {
      label: '运费',
      prop: 'shippingFee',
      type: 'number',
      precision: 2,
      rules: [
        { required: true, message: '请输入运费', trigger: 'blur' }
      ]
    },
    {
      label: '存储方法',
      prop: 'storageMethod',
      type: 'textarea',
      span: 24,
      minRows: 2,
      rules: [
        { required: true, message: '请输入存储方法', trigger: 'blur' }
      ]
    },
    {
      label: '商品描述',
      prop: 'description',
      type: 'textarea',
      span: 24,
      minRows: 4,
      overHidden: true,
      showOverflowTooltip: true,
      formslot: true,
      rules: [
        { required: true, message: '请输入商品描述', trigger: 'blur' }
      ]
    },
   
    {
      label: '是否热门',
      prop: 'isHot',
      type: 'switch',
      dicData: [
        { label: '是', value: 1 },
        { label: '否', value: 0 }
      ]
    },
    {
      label: '是否推荐',
      prop: 'isRecommend',
      type: 'switch',
      dicData: [
        { label: '是', value: 1 },
        { label: '否', value: 0 }
      ]
    },
    {
      label: '是否在售',
      prop: 'isOnSale',
      type: 'switch',
      dicData: [
        { label: '是', value: 1 },
        { label: '否', value: 0 }
      ],
      value: 1
    },
    {
      label: '创建时间',
      prop: 'createTime',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      addDisplay: false,
      editDisplay: false
    }
  ]
})

// 数据对象
const data = ref([])
const loading = ref(false)
const page = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 获取分类数据
const fetchCategories = async () => {
  try {
    const res = await getCategoryPage({
      current: 1,
      size: 100 // 获取足够多的分类数据
    })
    
    if (res.data.code === 200) {
      const categories = res.data.data.records || []
      const categoryOptions = categories.map(item => ({
        label: item.title,
        value: item.id
      }))
      
      // 更新下拉选项
      const categoryColumn = option.column.find(col => col.prop === 'categoryId')
      if (categoryColumn) {
        categoryColumn.dicData = categoryOptions
      }
    } else {
      ElMessage.error(res.data.msg || '获取分类数据失败')
    }
  } catch (error) {
    console.error('获取分类数据出错：', error)
    ElMessage.error('获取分类数据失败')
  }
}

// 加载数据
const onLoad = async (pagination, params) => {
  try {
    loading.value = true
    const queryParams = {
      pageNum: pagination?.currentPage || page.value.currentPage,
      pageSize: pagination?.pageSize || page.value.pageSize,
      ...params
    }
    
    const res = await getFruitPage(queryParams)
    if (res.data.code === 200) {
      const { records, total } = res.data.data
      data.value = records
      page.value = {
        ...page.value,
        total
      }
    } else {
      ElMessage.error(res.data.msg || '获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表出错：', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 新增记录
const onSubmit = async (row, done, loading) => {
  try {
    loading(true)
    const res = await addFruit(row)
    if (res.data.code === 200) {
      ElMessage.success('添加成功')
      done()
      onLoad(page.value)
    } else {
      ElMessage.error(res.data.msg || '添加失败')
    }
  } catch (error) {
    console.error('添加商品出错：', error)
    ElMessage.error('添加失败')
  } finally {
    loading(false)
  }
}

// 更新记录
const onUpdate = async (row, index, done, loading) => {
  try {
    loading(true)
    const res = await updateFruit(row)
    if (res.data.code === 200) {
      ElMessage.success('更新成功')
      done()
      onLoad(page.value)
    } else {
      ElMessage.error(res.data.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新商品出错：', error)
    ElMessage.error('更新失败')
  } finally {
    loading(false)
  }
}

// 删除记录
const onDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteFruit(row.id)
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      onLoad(page.value)
      return true
    } else {
      ElMessage.error(res.data.msg || '删除失败')
      return false
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品出错：', error)
      ElMessage.error('删除失败')
    }
    return false
  }
}

// 分页大小改变
const sizeChange = (val) => {
  page.value.pageSize = val
  onLoad(page.value)
}

// 当前页改变
const currentChange = (val) => {
  page.value.currentPage = val
  onLoad(page.value)
}

// 搜索条件改变
const searchChange = (params, done) => {
  onLoad(page.value, params)
  done()
}

// 重置搜索
const searchReset = () => {
  onLoad(page.value)
}

// 组件挂载时获取分类数据
onMounted(() => {
  fetchCategories()
})
</script>



<style scoped>
.product-container {
  background-color: var(--white-color);
  padding: var(--main-padding);
  border-radius: var(--border-radius);
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  position: relative;
}

.table-container {
  flex: 1;
  overflow: auto;
  position: relative;
}

:deep(.avue-crud__pagination) {
  position: sticky;
  bottom: 0;
  background-color: var(--white-color);
  margin-top: 16px;
  padding: 16px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

:deep(.avue-crud__menu) {
  background-color: var(--white-color);
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

</style> 